package com.everflourish.yeah100.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;

import com.everflourish.yeah100.utils.NotificationUtil;
import com.everflourish.yeah100.utils.SPUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;

public class VersionUpdateService extends Service {
    private Context mContext;
    private NotificationUtil mNotificationUtil;
    private int mMax = 100;
    private int mProgress;
    private String filePath = null;
    private String latestVersion = null;
    private int mFlagId;
    private SPUtil spUtil;
    private boolean isResume = false;
    private static final String TOTAL_LENGTH = "total_length";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        latestVersion = Yeah100.versionInfo.getLatestVersion();
        filePath = Environment.getExternalStorageDirectory() + "/"
                + Yeah100.versionInfo.getName() + "_v" + latestVersion + ".apk";
        final File file = new File(filePath);
        spUtil = SPUtil.getSharedPreferences(mContext, SPUtil.FILE_NAME);
        if (file.exists() && file.isFile()) {
            if (spUtil.getLong(TOTAL_LENGTH, -1) == -1) {
                file.delete();
            } else {
                isResume = true;
            }
        }
        HttpUtils http = new HttpUtils();
        HttpHandler handler = http.download(Yeah100.versionInfo.getUrl(),
                filePath, true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        mNotificationUtil = new NotificationUtil(mContext);
                        mFlagId = mNotificationUtil.showProgressNotify(mMax, 0,
                                "正在下载...", Yeah100.versionInfo.getName(),
                                "当前进度(0%)", null);
                    }

                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        if (isResume) {
                            total = spUtil.getLong(TOTAL_LENGTH, -1);
                        } else {
                            //发现如果是断点下载，返回的total是本地位下载完毕的大小。所以将total保存
                            spUtil.putLong(TOTAL_LENGTH, total);
                        }
                        if (current > total) {
                            return;
                        }
                        int progress = (int) (current * 100 / total);
                        if (progress - mProgress > 1) {
                            mProgress = progress;
                            mFlagId = mNotificationUtil.showProgressNotify(
                                    mMax, mProgress, "正在下载...",
                                    Yeah100.versionInfo.getName() + "_v"
                                            + latestVersion, "当前进度(" + progress
                                            + "%)", null);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        File file = responseInfo.result;
                        downLoadSuccess(file);
                    }

                    private void downLoadSuccess(File file) {
                        //判断大小是否一样，如果一样，则表示下载完成
                        /*if(file.length()!=spUtil.getLong(TOTAL_LENGTH, -1)){
                            //使用第三方下载...
							Uri uri = Uri.parse(Yeah100.versionInfo.getUrl());  
							Intent downloadIntent = new Intent(Intent.ACTION_VIEW, uri);  
							mContext.startActivity(downloadIntent); 
							return;
						}*/
                        spUtil.remove(TOTAL_LENGTH);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        intent.setDataAndType(Uri.fromFile(file),
                                "application/vnd.android.package-archive");
                        mNotificationUtil.cancelNotify(mFlagId);
                        VersionUpdateService.this.startActivity(intent);
                        stopSelf();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        if (spUtil.getLong(TOTAL_LENGTH, -1) == -1) {
                            file.delete();
                        } else if (spUtil.getLong(TOTAL_LENGTH, -1) != file.length()) {
                            file.delete();
                        } else if (msg.equals("maybe the file has downloaded completely")) {
                            downLoadSuccess(file);
                            return;
                        }
                        mNotificationUtil.showProgressNotify(mMax, mMax,
                                "下载失败", Yeah100.versionInfo.getName()
                                        + latestVersion, "下载失败", null);
                        if (file.exists() && file.isFile()) {
                            file.delete();
                        }
                        stopSelf();
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
